package service

import (
    "context"
    "gitee.com/WisdomClassroom/DisciplineStruct/glb"
    "gitee.com/WisdomClassroom/core"
    "gitee.com/WisdomClassroom/core/models"
    "gitee.com/WisdomClassroom/core/protobufs/v1/pb"
    "github.com/jinzhu/gorm"
)

func (s Service) ListCollegeDiscipline(_ context.Context, in *pb.ListCollegeDisciplineRequest) (*pb.ListCollegeDisciplineResponse, error) {
    token := core.NewToken()
    err := token.UnpackToken(in.AuthToken, &core.FlagTokenCert)
    if err != nil {
        return &pb.ListCollegeDisciplineResponse{Status: &pb.ResponseStatus{
            Code: pb.ResponseStatusCode_NotAuth, Error: err.Error(),
        },}, nil
    }

    if len(in.CollegeUUID) != 36 {
        return &pb.ListCollegeDisciplineResponse{Status: &pb.ResponseStatus{Code: pb.ResponseStatusCode_OtherError,
            Message: "学院编号不正确",
        },}, nil
    }

    college := models.CollegeModel{
        Model: models.Model{
            UUID: in.CollegeUUID,
        },
    }
    err = glb.DB.Scopes(notDeleted).Where(&college).First(&college).Error
    if err == gorm.ErrRecordNotFound {
        return &pb.ListCollegeDisciplineResponse{Status: &pb.ResponseStatus{Code: pb.ResponseStatusCode_OtherError,
            Message: "学院编号不存在",
        },}, nil
    } else if err != nil {
        glb.Logger.Error(err.Error())
        return listCollegeDisciplineRespSvrErr, nil
    }

    var dsplnRespUnits []*pb.ListDisciplineResponseUnit

    // 从学院逐级向下读取
    var collegeDsplnBinds []models.CollegeDisciplineBindModel
    err = glb.DB.Scopes(notDeleted).Where("college_uuid=?", in.CollegeUUID).Find(&collegeDsplnBinds).Error
    if err == nil {
        // 存在专业记录
        var disciplineUUIDs []string
        for _, collegeDisciplineBind := range collegeDsplnBinds {
            disciplineUUIDs = append(disciplineUUIDs, collegeDisciplineBind.DisciplineUUID)
        }

        var disciplines []models.DisciplineModel
        err = glb.DB.Scopes(notDeleted).Where("uuid IN(?)", disciplineUUIDs).Find(&disciplines).Error
        if err != nil {
            glb.Logger.Error(err.Error())
            return listCollegeDisciplineRespSvrErr, nil
        }

        var dsplnMngrBinds []*models.DisciplineManagerBindModel
        err = glb.DB.Scopes(notDeleted).Where("discipline_uuid IN(?)", disciplineUUIDs).Find(&dsplnMngrBinds).Error
        if err != nil && err != gorm.ErrRecordNotFound {
            glb.Logger.Error(err.Error())
            return listCollegeDisciplineRespSvrErr, nil
        }

        dsplnRespUnitsMap := make(map[string]*pb.ListDisciplineResponseUnit)
        for _, discipline := range disciplines {
            dsplnRespUnitsMap[discipline.UUID] = &pb.ListDisciplineResponseUnit{
                UUID:        discipline.UUID,
                Name:        discipline.Name,
                Description: discipline.Description,
                CollegeUUID: in.CollegeUUID,
            }
        }
        for _, dsplnMngrBind := range dsplnMngrBinds {
            dsplnRespUnitsMap[dsplnMngrBind.DisciplineUUID].ManagerUUID =
                append(dsplnRespUnitsMap[dsplnMngrBind.DisciplineUUID].ManagerUUID, dsplnMngrBind.ManagerUUID)
        }

        for _, dsplnRespUnit := range dsplnRespUnitsMap {
            dsplnRespUnits = append(dsplnRespUnits, dsplnRespUnit)
        }
    } else if err != gorm.ErrRecordNotFound {
        glb.Logger.Error(err.Error())
        return listCollegeDisciplineRespSvrErr, nil
    }

    return &pb.ListCollegeDisciplineResponse{
        Status:      &pb.ResponseStatus{Code: pb.ResponseStatusCode_Suc},
        Disciplines: dsplnRespUnits,
    }, nil
}
